#pragma Once
#include "Socket.hpp"
#include <iostream>
#include <memory>
#include "Epoller.hpp"
class EpollServer:public nocopy
{
    static const int num = 64; // struct epoll_event[] 的大小
public:
    EpollServer(uint16_t port)
        : _port(port),
          _LisSock_ptr(new Sock()),
          _epoller_ptr(new Epoller())
    {
    }

    void Init()
    {
        _LisSock_ptr->Socket();
        _LisSock_ptr->Bind(_port);
        _LisSock_ptr->Listen();
        lg(Info, "listen sucess fd: %d", _LisSock_ptr->Getfd());
    }

    void Accepter()
    {
        uint16_t clientport;
        std::string clientip;
        int sock = _LisSock_ptr->Accept(&clientip, &clientport);
        if (sock > 0)
        {
            _epoller_ptr->EpollerCtl(EPOLL_CTL_ADD, sock, EPOLLIN);
            lg(Info, "get a new link, client info@ %s:%d", clientip.c_str(), clientport);
        }
    }

    void Recv(int fd)
    {
        char buffer[1024];
        int n = read(fd, buffer, sizeof(buffer) - 1);   // 存在问题！！
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a messge: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            lg(Info, "client quit, me too, close fd is : %d", fd);

            // 这里需要先 epoll_ctl，再close
            _epoller_ptr->EpollerCtl(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            lg(Warning, "recv error: fd is : %d", fd);
            _epoller_ptr->EpollerCtl(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
    }

    void Dispatcher(struct epoll_event revents[], int num)
    {
        for (int i = 0; i < num; i++)
        {
            if (revents[i].events & EPOLLIN)
            {
                if (revents[i].data.fd == _LisSock_ptr->Getfd())
                {
                    Accepter();
                }
                else
                {
                    Recv(revents[i].data.fd);
                }
            }
        }
    }

    void Start()
    {
        // 将listensock添加到epoll中 -> listensock和他关心的事件，添加到内核epoll模型中rb_tree.
        _epoller_ptr->EpollerCtl(EPOLL_CTL_ADD, _LisSock_ptr->Getfd(), EPOLLIN);
        struct epoll_event revs[num];
        while (true)
        {
            // epoll_wait
            int n = _epoller_ptr->EpollerWait(revs, num);
            if (n > 0)
            {
                // 有事件就绪
                lg(Debug, "event happened ....");
                Dispatcher(revs, n);
            }
            else if (n == 0)
            {
                lg(Info, "time out ...");
            }
            else
            {
                lg(Error, "epll wait error:%s", strerror(errno));
            }
        }
    }

    ~EpollServer()
    {
        _LisSock_ptr->Close();
    }

private:
    std::shared_ptr<Sock> _LisSock_ptr;    // 监听套接字
    std::shared_ptr<Epoller> _epoller_ptr; // epoll
    uint16_t _port;                        // 端口
};